import { atom, selector } from "recoil";

// 创建一个待办事项的初始化状态
const todoListState = atom({
  key: "todoListState",
  default: [
    {
      content: "去超市购物🛍️",
      isCompleted: false,
      time: 1291088702174,
    },
    {
      content: "学习 Go 语言",
      isCompleted: false,
      time: 1493088702174,
    },
    {
      content: "了解 Bun 相关的信息",
      isCompleted: true,
      time: 1592088502174,
    },
    {
      content: "准备 Bun 相关的公开课",
      isCompleted: false,
      time: 1695088702174,
    },
  ],
});

// 创建一个 selecor 计算属性用于计算时间
// 从而显示标准格式的时间
const timeFormatedTodoListState = selector({
  key: "timeFormatedTodoListState",
  get: ({ get }) => {
    // 通过 get 方法拿到所有的待办事项的状态数据
    const todoList = get(todoListState);
    // 接下来在该状态数据的基础上进行一个二次计算
    return todoList.map((item) => {
      const time = new Date(item.time);
      const year = time.getFullYear(); // 年
      const month = time.getMonth() + 1; // 月
      const date = time.getDate(); // 日
      const hour = time.getHours(); // 时
      const minute = time.getMinutes(); // 分
      return {
        ...item,
        time: `${year}/${month}/${date} ${hour}:${minute}`,
      };
    });
  },
});

// 创建一个 selector 计算属性用于计算各种状态
const todoListStatus = selector({
  key: "todoListStatus",
  get: ({ get }) => {
    const todoList = get(todoListState);
    // 总项目数
    const totalNum = todoList.length;
    // 完成项目数
    const completedNum = todoList.filter((item) => item.isCompleted).length;
    // 未完成项目数
    const uncompletedNum = totalNum - completedNum;
    // 完成项目百分比
    const percentCompleted =
      totalNum === 0 ? 0 : Math.round((completedNum / totalNum) * 100);

    // 未完成项目对应的内容文本
    const allText: string[] = [];
    todoList.forEach((item) => {
      if (!item.isCompleted) {
        allText.push(item.content);
      }
    });

    return {
      totalNum,
      completedNum,
      uncompletedNum,
      percentCompleted,
      allText,
    };
  },
});

// select 的状态值
const todoListFilterState = atom({
  key: "todoListFilterState",
  default: "all",
});

// 接下来就应该根据 select 的状态值对 timeFormatedTodoListState 进行过滤
const todoListFilteredItem = selector({
  key: "todoListFilteredItem",
  get: ({ get }) => {
    // 获取时间处理过的待办事项
    const list = get(timeFormatedTodoListState);
    // 获取 select 的状态值
    const filter = get(todoListFilterState);
    // 进行过滤
    switch (filter) {
      case "completed":
        return list.filter((item) => item.isCompleted);
      case "uncompleted":
        return list.filter((item) => !item.isCompleted);
      default:
        return list;
    }
  },
});

export {
  todoListState,
  timeFormatedTodoListState,
  todoListStatus,
  todoListFilterState,
  todoListFilteredItem,
};
